package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

//ChartRecord 客户会话记录
type ChartRecord struct {
	Id uint `json:"id" orm:"pk;auto"`
	ChartId uint `json:"chart_id"`
	Content string `json:"content" description:"内容"`
	Uid uint `json:"uid" description:"用户id"`
	Types uint `json:"type" description:"1.顾客 2.客服"`
	CreatedAt time.Time `json:"created_at" orm:"auto_now_add;type(datetime)"`
	Status uint `json:"status" description:"1.有效 0.无效"`
}

func init()  {
	orm.RegisterModel(new(ChartRecord))
}

//ChartRecordAdd 新增会话记录
func ChartRecordAdd(chartId uint, content string, uid, types uint) ChartRecord {
	obj := ChartRecord{
		ChartId:   chartId,
		Content:   content,
		Uid:       uid,
		Types:     types,
		CreatedAt: time.Now(),
		Status:    1,
	}
	o := orm.NewOrm()
	i, err := o.Insert(&obj)
	if	err != nil {
		panic(err)
	}
	obj.Id = uint(i)

	return obj
}

//ChartRecordHistory 聊天记录
func ChartRecordHistory(chartId, lastId uint, size int) (result []ChartRecord) {
	o := orm.NewOrm()

	query := o.QueryTable(ChartRecord{}).Filter("status", 1).Filter("chart_id", chartId)
	if lastId > 0 {
		query = query.Filter("id__lt", lastId)
	}

	query.OrderBy("-id").Limit(size).All(&result)

	return
}